package com.my12306.user.util.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.my12306.common.enums.CodeEnum;
import com.my12306.common.util.response.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("ssbAuthenctiationFailureHandler")
public class LonginAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;


    /* (non-Javadoc)
     * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
     */

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        System.out.println("----------faiule-------");
        response.setContentType("application/json;charset=UTF-8");
        ResponseData fail = ResponseData.fail(CodeEnum.FAIL.getCode(), exception.getMessage());

        response.getWriter().write(objectMapper.writeValueAsString(fail));

    }
}
